package com.yuncheng.oaApi.lcService;

import com.yuncheng.oaApi.utils.GetUuIdUtils;;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaFlowConstants;
import com.yuncheng.oaApi.entity.OaJobEntity;
import com.yuncheng.oaApi.service.IOaSpcySqsxJobService;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.oaApi.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component(value = "flowService1")
public class OaFlowService {

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private OalgqsOaFlowService oalgqsFlowService;

    @Resource
    @Lazy
    private OaGwycOaFlowService oaGwycFlowService;

    @Resource
    @Lazy
    private OaHsyglOaFlowService oaHsyglFlowService;

    @Resource
    @Lazy
    private OaXzswspOaFlowService oaXzswspFlowService;

    @Resource
    @Lazy
    private OaXcxxspglOaFlowService oaXcxxspglFlowService;

    @Resource
    @Lazy
    private OaBgypsqglOaFlowService oaBgypsqglFlowService;

    @Resource
    @Lazy
    private OaSwOaFlowService oaSwFlowService;

    @Resource
    @Lazy
    private OaqxjOaFlowService oaqxjFlowService;


    @Resource
    @Lazy
    private OajbzbOaFlowService oajbzbFlowService;

    //初始化任务,创建好业务记录以后调用
    public Result initJob(OaFlowConstants oaFlowConstants, String pid, CurrentUserVo currentUser) {
        String nodeName = oaFlowConstants.getFirstNode();
        //需要校验是否已经初始化过
        List<OaJobEntity> list = spcySqsxJobService.list(new LambdaQueryWrapper<OaJobEntity>()
                .eq(OaJobEntity::getFpid, pid)
                .eq(OaJobEntity::getFhjmc, nodeName)
                .ne(OaJobEntity::getFblzt, OaCommonFlowConstant.BLZT_YB)
        );
       /* if(list.size()>0){
            return Result.error("该事项存在待办任务");
        }*/
       if(list.size()>0){
           List<String> ids = list.stream().map(OaJobEntity::getId).collect(Collectors.toList());
           spcySqsxJobService.removeBatchByIds(ids);
       }
        return createNextJob(oaFlowConstants,pid,null,currentUser,nodeName,"");
    }


    public Result passJob(OaFlowConstants oaFlowConstants, String pid, String jobId, String opinion, String nextNodeName, String nextNodeDbrIds) {
       return passJob(oaFlowConstants, pid, jobId, opinion, nextNodeName, nextNodeDbrIds,true);
    }

    /**
     * 提交任务
     * @param pid 业务表id
     * @param jobId 待提交的jobId
     * @param opinion 办理意见
     * @param nextNodeName 下一环节名称（可空）
     * @param nextNodeDbrIds 下一环节办理人（可空）
     * @return
     */
    public Result passJob(OaFlowConstants oaFlowConstants, String pid, String jobId, String opinion, String nextNodeName, String nextNodeDbrIds, boolean isOverCurrentJob){

        // 获得当前待办任务，并做校验
        OaJobEntity job= spcySqsxJobService.getById(jobId);
        if (job==null){
            return Result.error("查不到id为【"+jobId+"】的待办任务");
        }

        //获取办理人，并做办理人的校验，如果当前登录人不是待办人之一，拒绝办理
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null){
            return Result.error("请先登录");
        }
        if(isOverCurrentJob){
            //办理掉当前环节
            Result result = doJob(job,currentUser,opinion);
            //生成下一环节的待办
            if(result.isSuccess()){
                job = (OaJobEntity)result.getResult();
                if(job.getFblzt().equals(OaCommonFlowConstant.BLZT_YB)){
                    //创建下一环节任务
                    Result result1= createNextJob(oaFlowConstants,pid,job,currentUser,nextNodeName,nextNodeDbrIds);
                    if (!result1.isSuccess()){
                        return Result.error(result1.getMessage());
                    }else {
                        // 3-16 返回新增的流程任务
                        return Result.ok(result1.getResult());
                    }
                }
                // 3-16 返回当前流程任务
                return Result.ok(job);
            }else{
                return Result.error(result.getMessage());
            }
        }else{
            //请小陈完善

            //创建下一环节任务
            Result result1= createNextJob(oaFlowConstants,pid,job,currentUser,nextNodeName,nextNodeDbrIds);
            if (!result1.isSuccess()){
                return Result.error(result1.getMessage());
            }else {
                // 3-16 返回新增的流程任务
                return Result.ok(result1.getResult());
            }
        }


    }

    /**
     *
     * @param job
     * @param currentUser
     */
    private Result doJob(OaJobEntity job, CurrentUserVo currentUser, String opinion){
        String blrId = "";
        String blr = "";
        if (currentUser != null) {
            blrId = currentUser.getId();
            blr = currentUser.getName();
        }

        if(OaCommonFlowConstant.BLZT_YB.equals(job.getFblzt())){
            return Result.error("当前任务已提交");
        }
        if(StringUtils.isBlank(job.getFdbrid())){
            return Result.error("当前任务未指定办理人");
        }
        if(!job.getFdbrid().contains(blrId)){
            return Result.error("当前登录用户无此任务的办理权限");
        }
        // 办理方式 竞争办理 、多人线性办理 、多人并行办理
        String blfs = job.getFblfs();
        if(StringUtils.isBlank(blfs)||blfs.equals(OaCommonFlowConstant.BLFS_DRJJ)){
            job.setFblr(blr);
            job.setFblsj(new Date());
            job.setFblyj(opinion);
            job.setFblzt(OaCommonFlowConstant.BLZT_YB);
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }else if(blfs.equals(OaCommonFlowConstant.BLFS_DRXX)  || blfs.equals(OaCommonFlowConstant.BLFS_DRBX)){
            //先根据多个人线性和多人并行的逻辑获得下一办理人
            String nextBlrId ="";
            String nextBlr ="";
            if(blfs.equals(OaCommonFlowConstant.BLFS_DRXX)){
                String ydbrIds[] = job.getFydbrid().split(",");
                String ydbrs[] = job.getFydbr().split(",");
                for (int i=0;i<ydbrIds.length;i++){
                    String dbrId = ydbrIds[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(dbrId.equals(blrId)){
                        if(i+1<ydbrIds.length){
                            nextBlrId=ydbrIds[i+1];
                            nextBlr=ydbrs[i+1];
                            break;
                        }
                    }
                }
            }else{
                String dbrIds[] = job.getFdbrid().split(",");
                String dbrs[] = job.getFdbr().split(",");
                for (int i=0;i<dbrIds.length;i++){
                    String dbrId = dbrIds[i];
                    String dbr = dbrs[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(!dbrId.equals(blrId)){
                        nextBlrId=nextBlrId+(StringUtils.isBlank(nextBlrId)?"":",")+dbrId;
                        nextBlr=nextBlr+(StringUtils.isBlank(nextBlr)?"":",")+dbr;
                    }
                }
            }

            //如果存在下一办理人 就继续待办，多人办理意见用@@分隔，办理时间、办理人、意见 用|分隔
            job.setFblr(blr);
            job.setFblsj(new Date());
            String blyj=(job.getFblyj()==null?"":job.getFblyj())+(StringUtils.isBlank(job.getFblyj())?"":"@@")+ DateConversionUtils.DateToString(new Date()) +"|"+blr+"|"+ opinion;
            job.setFblyj(blyj);
            if(StringUtils.isBlank(nextBlrId)){
                job.setFblzt(OaCommonFlowConstant.BLZT_YB);
            }else{
                job.setFblzt(OaCommonFlowConstant.BLZT_DB);
                job.setFdbrid(nextBlrId);
                job.setFdbr(nextBlr);
            }
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }
        return Result.error("待办任务未指定办理方式");
    }

    /**
     *
     * @param pid
     * @param currentJob
     * @param currentUser
     * @param nextNodeName
     * @param nextNodeDbrIds
     * @return
     */
    public Result createNextJob(OaFlowConstants oaFlowConstants, String pid, OaJobEntity currentJob, CurrentUserVo currentUser, String nextNodeName, String nextNodeDbrIds){
        if (currentJob != null) {
            nextNodeName = getNextNodeName(oaFlowConstants, currentJob.getFhjmc(), nextNodeName);
        }else {
            nextNodeName = getNextNodeName(oaFlowConstants, "", nextNodeName);
        }
        if(nextNodeName.equals(oaFlowConstants.HJMC_LCJS)){
            OaJobEntity job = new OaJobEntity();

            return Result.ok(job);
        }
        Map map = new HashMap();
            if (oaFlowConstants.getFywflcode().equals("oalgqs001")) {
            // oa-离岗请示流程
            map = oalgqsFlowService.getNodeDbr(pid,nextNodeName, nextNodeDbrIds);
        } else if (oaFlowConstants.getFywflcode().equals("oagwcsq001")){
            //oa-公务用车申请流程
            map = oaGwycFlowService.getNodeDbr(pid,nextNodeName, nextNodeDbrIds);
        } else if(oaFlowConstants.getFywflcode().equals("oahysgl001")){
            //oa-会议室申请管理
            map = oaHsyglFlowService.getNodeDbr(pid,nextNodeName, nextNodeDbrIds);
        } else if (oaFlowConstants.getFywflcode().equals("oaxzswsp001")){
                //oa-行政事务审批
            map = oaXzswspFlowService.getNodeDbr(pid,nextNodeName, nextNodeDbrIds);
        }else if (oaFlowConstants.getFywflcode().equals("oaxcxxspgl001")){
                //oa-宣传信息审批
            map = oaXcxxspglFlowService.getNodeDbr(pid,nextNodeName, nextNodeDbrIds);
        }else if (oaFlowConstants.getFywflcode().equals("oabgypsqgl001")) {
                //oa-办公用品申请管理
            map = oaBgypsqglFlowService.getNodeDbr(pid, nextNodeName, nextNodeDbrIds);
        } else if (oaFlowConstants.getFywflcode().equals("oasw001")) {
                //oa-收文管理
            map = oaSwFlowService.getNodeDbr(pid, nextNodeName, nextNodeDbrIds);
        } else if (oaFlowConstants.getFywflcode().equals("oaqxjgl001")) {
                //oa-请休假审批
//            map = oaqxjFlowService.getNodeDbr(pid, nextNodeName, nextNodeDbrIds);
        } else if (oaFlowConstants.getFywflcode().equals("oajbzbgl001")) {
                //oa-加班值班
            map = oajbzbFlowService.getNodeDbr(pid, nextNodeName, nextNodeDbrIds);
        }

        nextNodeDbrIds = map.get("dbrId").toString();
        String nextNodeDbrs = map.get("dbr").toString();
        if(StringUtils.isBlank(nextNodeDbrIds)){
            return Result.error("获取不到下一环节待办人");
        }
        OaJobEntity job = new OaJobEntity();
        job.setId(GetUuIdUtils.generateUuid());
        if(currentJob!=null){
            job.setFsyhjid(currentJob.getId());
        }
        job.setFpid(pid);
        job.setFhjmc(nextNodeName);
        if(currentUser != null) {
            job.setFfsrid(currentUser.getId());
            job.setFfsrmc(currentUser.getName());
        }
        job.setFfssj(new Date());

        job.setFdbrid(nextNodeDbrIds);
        job.setFdbr(nextNodeDbrs);
        job.setFydbrid(nextNodeDbrIds);
        job.setFydbr(nextNodeDbrs);

        job.setFblfs(oaFlowConstants.getBlfs(nextNodeName));
        job.setFblzt(OaCommonFlowConstant.BLZT_DB);
        job.setFlcmc(oaFlowConstants.getFlowName()); // 2023-4-3 流程名称
        spcySqsxJobService.save(job);
        return Result.ok(job);
    }

    private String getNextNodeName(OaFlowConstants oaFlowConstants, String  currentNodeName, String nextNodeName){
        if (StringUtils.isNotBlank(nextNodeName)){
            return nextNodeName;
        }else{
           return oaFlowConstants.getNextNodeName(currentNodeName);
        }
    }


}
